package cn.ug.pay.web.controller;

import cn.ug.aop.RequiresPermissions;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Order;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.Config;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.login.LoginHelper;
import cn.ug.pay.bean.BillBean;
import cn.ug.pay.bean.FeeBean;
import cn.ug.pay.bean.YeepayBill;
import cn.ug.pay.bean.request.FinanceBillParam;
import cn.ug.pay.bean.response.ActiveMemberBean;
import cn.ug.pay.bean.type.TradeType;
import cn.ug.pay.mapper.entity.PayYeepayBill;
import cn.ug.pay.service.BillService;
import cn.ug.pay.service.PayYeepayBillService;
import cn.ug.util.BigDecimalUtil;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import cn.ug.web.controller.ExportExcelController;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static cn.ug.util.ConstantUtil.COMMA;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 收支记录管理
 * @author kaiwotech
 */
@RestController
@RequestMapping("bill")
public class BillController extends BaseController {

    @Resource
    private BillService billService;
    @Autowired
    private PayYeepayBillService payYeepayBillService;
    @Resource
    private Config config;

    @PostMapping("/yeepay/import")
    public SerializeObject importBills(@RequestHeader String accessToken, Integer type, HttpServletRequest request) {
        type = type == null ? 0 : type;
        if (type != 1 && type != 2) {
            return new SerializeObjectError("00000002");
        }
        List<PayYeepayBill> bills = new ArrayList<PayYeepayBill>();
        CommonsMultipartResolver multipartResolver  = new CommonsMultipartResolver(request.getSession().getServletContext());
        if(multipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            Iterator<String> iterator = multiRequest.getFileNames();
            while(iterator.hasNext()){
                MultipartFile file = multiRequest.getFile(iterator.next());
                BufferedReader br= null;
                try {
                    InputStreamReader isr = new InputStreamReader(file.getInputStream(),"utf-8");
                    br = new BufferedReader(isr);
                    String line = "";
                    int index = 0;
                    if (type == 1) {
                        while ((line = br.readLine()) != null) {
                            index ++;
                            if(index == 1){
                                continue;
                            }
                            if(StringUtils.isNotBlank(line)){
                                if(line.split(COMMA).length == 16){
                                    String[] infos = line.split(COMMA);
                                    PayYeepayBill bill = new PayYeepayBill();
                                    bill.setSettleTime(infos[1]);
                                    bill.setPayTime(infos[3]);
                                    bill.setOrderNO(infos[4]);
                                    bill.setSerialNO(infos[5]);
                                    if (StringUtils.isNotBlank(infos[6])) {
                                        bill.setAmount(new BigDecimal(infos[6]));
                                    } else {
                                        bill.setAmount(BigDecimal.ZERO);
                                    }
                                    if (StringUtils.isNotBlank(infos[9])) {
                                        bill.setFee(new BigDecimal(infos[9]));
                                    } else {
                                        bill.setAmount(BigDecimal.ZERO);
                                    }
                                    if (StringUtils.equals(StringUtils.trim(infos[14]), "支付成功")) {
                                        bill.setStatus(1);
                                    }
                                    bill.setType(type);
                                    bills.add(bill);
                                }
                            }
                        }
                        if (bills != null && bills.size() > 0) {
                            if (payYeepayBillService.save(bills)) {
                                return new SerializeObject(ResultType.NORMAL, "00000001");
                            } else {
                                return new SerializeObject(ResultType.ERROR, "00000005");
                            }
                        } else {
                            return new SerializeObjectError("17002033");
                        }
                    } else {
                        while ((line = br.readLine()) != null) {
                            index ++;
                            if(index == 1){
                                continue;
                            }
                            if(StringUtils.isNotBlank(line)){
                                String[] infoss = line.split(COMMA);
                                String[] a = StringUtils.split(line, COMMA);
                                int length = line.split(COMMA).length;
                                if(line.split(COMMA).length == 12 || line.split(COMMA).length == 11){
                                    String[] infos = line.split(COMMA);
                                    PayYeepayBill bill = new PayYeepayBill();
                                    bill.setOrderNO(infos[1]);
                                    bill.setSerialNO(infos[2]);
                                    bill.setPayTime(infos[3]);
                                    if (StringUtils.isNotBlank(infos[4])) {
                                        bill.setAmount(new BigDecimal(infos[4]));
                                    } else {
                                        bill.setAmount(BigDecimal.ZERO);
                                    }
                                    if (StringUtils.isNotBlank(infos[5])) {
                                        bill.setFee(new BigDecimal(infos[5]));
                                    } else {
                                        bill.setAmount(BigDecimal.ZERO);
                                    }
                                    if (StringUtils.equals(StringUtils.trim(infos[9]), "WITHDRAW_SUCCESS")) {
                                        bill.setStatus(1);
                                    }
                                    bill.setSettleTime(infos[10]);
                                    bill.setType(type);
                                    bills.add(bill);
                                }
                            }
                        }
                        if (bills != null && bills.size() > 0) {
                            if (payYeepayBillService.save(bills)) {
                                return new SerializeObject(ResultType.NORMAL, "00000001");
                            } else {
                                return new SerializeObject(ResultType.ERROR, "00000005");
                            }
                        } else {
                            return new SerializeObjectError("17002033");
                        }
                    }
                } catch (Exception e) {
                    return new SerializeObjectError("17002032");
                }finally{
                    if(br!=null){
                        try{
                            br.close();
                            br=null;
                        }catch(IOException e){
                            e.printStackTrace();
                            info(e.getMessage());
                        }
                    }
                }
            }
        }
        return new SerializeObjectError("17002031");
    }

    /**
     * 根据ID查找信息
     * @param id		    ID
     * @return			    记录集
     */
    @RequestMapping(value = "{id}", method = GET)
    public SerializeObject find(@PathVariable String id) {
        if(StringUtils.isBlank(id)) {
            return new SerializeObjectError("00000002");
        }
        BillBean entity = billService.findById(id);
        if(null == entity || StringUtils.isBlank(entity.getId())) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @GetMapping("/member/amount")
    public SerializeObject getAmount(String memberId) {
        memberId = UF.toString(memberId);
        if(StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000002");
        }
        JSONObject result = new JSONObject();
        result.put("rechargeAmount", billService.sumAmount(TradeType.ONLINE_RECHARGE.getValue(), "", "", memberId));
        result.put("withdrawAmount", billService.sumAmount(TradeType.ACCOUNT_WITHDRAWAL.getValue(), "", "", memberId));
        return new SerializeObject<>(ResultType.NORMAL, result);
    }

    @GetMapping("/amount")
    public SerializeObject getAmount(@RequestHeader String accessToken, int tradeType, String startDate,String endDate) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        JSONObject result = new JSONObject();
        result.put("amount", billService.sumAmount(tradeType, startDate, endDate, ""));
        result.put("members", billService.sumMembers(tradeType, startDate, endDate, ""));
        return new SerializeObject<>(ResultType.NORMAL, result);
    }

    @GetMapping(value = "/yeepay/list")
    public SerializeObject<DataTable<YeepayBill>> listBills(@RequestHeader String accessToken, Page page, String memberId) {
        memberId = UF.toString(memberId);
        int total = payYeepayBillService.count(memberId);
        page.setTotal(total);
        if (total > 0) {
            List<YeepayBill> list = payYeepayBillService.query(memberId, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<YeepayBill>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<YeepayBill>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<YeepayBill>()));
    }

    @GetMapping(value = "/yeepay/fee/export")
    public void exportYeepayFeeData(HttpServletResponse response, Integer type, String mobile, String name, String startDate, String endDate) {
        mobile = UF.toString(mobile);
        name = UF.toString(name);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        type = type == null ? 0 : type;
        List<FeeBean> list = payYeepayBillService.queryYeepayFee(type, mobile, name, startDate, endDate, 0, 0);
        if(list != null && list.size() > 0){
            String[] columnNames = { "序号","手机号", "用户姓名", "操作类型", "金额（元）", "黄金克重（克）",  "易宝手续费（元）",
                    "平台手续费（元）", "实收手续费（元）", "操作时间"};
            String [] columns = {"index", "mobile", "name", "remark", "amount", "gram", "yeepayFee", "fee", "actualFee", "payTime"};
            String fileName = "易宝手续费对账表";
            int index = 1;
            for (FeeBean bean : list) {
                bean.setIndex(index);
                index++;
            }
            ExportExcelController<FeeBean> export = new ExportExcelController<FeeBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/yeepay/fee/list")
    public SerializeObject<DataTable<FeeBean>> listYeepayFeeBills(@RequestHeader String accessToken, Page page, Integer type, String mobile, String name, String startDate, String endDate) {
        mobile = UF.toString(mobile);
        name = UF.toString(name);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        type = type == null ? 0 : type;
        int total = payYeepayBillService.countYeepayFee(type, mobile, name, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<FeeBean> list = payYeepayBillService.queryYeepayFee(type, mobile, name, startDate, endDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<FeeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<FeeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<FeeBean>()));
    }

    @GetMapping(value = "/fee/export")
    public void exportData(HttpServletResponse response, Integer type, String mobile, String name, String startDate, String endDate) {
        mobile = UF.toString(mobile);
        name = UF.toString(name);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        type = type == null ? 0 : type;
        List<FeeBean> list = payYeepayBillService.queryFee(type, mobile, name, startDate, endDate, 0, 0);
        if(list != null && list.size() > 0){
            String[] columnNames = { "序号","手机号", "用户姓名", "操作类型", "金额（元）", "黄金克重（克）",  "易宝手续费（元）",
                    "平台手续费（元）", "实收手续费（元）", "操作时间"};
            String [] columns = {"index", "mobile", "name", "remark", "amount", "gram", "yeepayFee", "fee", "actualFee", "payTime"};
            String fileName = "手续费明细表";
            int index = 1;
            for (FeeBean bean : list) {
                bean.setIndex(index);
                index++;
            }
            ExportExcelController<FeeBean> export = new ExportExcelController<FeeBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/fee/list")
    public SerializeObject<DataTable<FeeBean>> listFeeBills(@RequestHeader String accessToken, Page page, Integer type, String mobile, String name, String startDate, String endDate) {
        mobile = UF.toString(mobile);
        name = UF.toString(name);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        type = type == null ? 0 : type;
        int total = payYeepayBillService.countFee(type, mobile, name, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<FeeBean> list = payYeepayBillService.queryFee(type, mobile, name, startDate, endDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<FeeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<FeeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<FeeBean>()));
    }

    /**
     * 发起申请
     * @param accessToken		登录成功后分配的Key
     * @param entity		    记录集
     * @return				    是否操作成功
     */
    @RequiresPermissions("pay:bill:update")
    @RequestMapping(method = POST)
    public SerializeObject update(@RequestHeader String accessToken, BillBean entity) {
        if(null == entity || BigDecimalUtil.isZeroOrNull(entity.getAmount())) {
            return new SerializeObjectError("00000002");
        }
        String memberId = LoginHelper.getLoginId();
        if(StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        entity.setMemberId(memberId);
        billService.save(entity);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 根据当前登录用户查询数据
     * @param accessToken	    登录成功后分配的Key
     * @param order		        排序
     * @param page		        分页
     * @param type			    类型 1:收入 2:支出
     * @param tradeType		    交易类型 1:线上充值  2:卖金收入 3:邀请返现 4:账户提现 5:买金支出
     * @param addTimeMinString	最小操作时间(yyyy-MM-dd)
     * @param addTimeMaxString  最大操作时间(yyyy-MM-dd)
     * @return			        分页数据
     */
    @RequestMapping(value = "queryByMemberId", method = GET)
    public SerializeObject<DataTable<BillBean>> queryByMemberId(@RequestHeader String accessToken, Order order, Page page, Integer type, Integer tradeType, String addTimeMinString, String addTimeMaxString) {
        if(page.getPageSize() <= 0) {
            page.setPageSize(config.getPageSize());
        }
        if(null == type || type < 0) {
            type = 0;
        }
        if(null == tradeType || tradeType < 0) {
            tradeType = 0;
        }
        LocalDateTime addTimeMin = null;
        LocalDateTime addTimeMax = null;
        if(StringUtils.isNotBlank(addTimeMinString)) {
            addTimeMin = UF.getDate(addTimeMinString);
        }
        if(StringUtils.isNotBlank(addTimeMaxString)) {
            addTimeMax = UF.getDate(addTimeMaxString);
        }
        String memberId = LoginHelper.getLoginId();
        if(StringUtils.isBlank(memberId)) {
            return new SerializeObjectError<>("00000102");
        }

        DataTable<BillBean> dataTable = billService.query(order.getOrder(), order.getSort(), page.getPageNum(), page.getPageSize(), type, tradeType,
                null, null, addTimeMin, addTimeMax, memberId, null, null, null);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }

    /**
     * 查询数据
     * @param accessToken	        登录成功后分配的Key
     * @param order		            排序
     * @param page		            分页
     * @param type			        类型 1:收入 2:支出
     * @param tradeType		        交易类型 1:线上充值  2:卖金收入 3:邀请返现 4:账户提现 5:买金支出
     * @param amountMin		        最小收支记录金额
     * @param amountMax		        最大收支记录金额
     * @param addTimeMinString	    最小操作时间
     * @param addTimeMaxString	    最大操作时间
     * @param memberId		        会员ID
     * @param memberName	        会员名称
     * @param memberMobile	        会员手机
     * @param keyword		        关键字
     * @return			            分页数据
     */
    @RequestMapping(method = GET)
    public SerializeObject<DataTable<BillBean>> query(@RequestHeader String accessToken, Order order, Page page, Integer type, Integer tradeType,
                                                          BigDecimal amountMin, BigDecimal amountMax,
                                                          String addTimeMinString, String addTimeMaxString,
                                                          String memberId, String memberName, String memberMobile, String keyword) {
        if(page.getPageSize() <= 0) {
            page.setPageSize(config.getPageSize());
        }
        if(null == type || type < 0) {
            type = 0;
        }
        if(null == tradeType || tradeType < 0) {
            tradeType = 0;
        }
        LocalDateTime addTimeMin = null;
        LocalDateTime addTimeMax = null;
        if(StringUtils.isNotBlank(addTimeMinString)) {
            addTimeMin = UF.getDate(addTimeMinString);
        }
        if(StringUtils.isNotBlank(addTimeMaxString)) {
            addTimeMax = UF.getDate(addTimeMaxString);
        }
        keyword = UF.toString(keyword);

        DataTable<BillBean> dataTable = billService.query(order.getOrder(), order.getSort(), page.getPageNum(), page.getPageSize(), type, tradeType,
                amountMin, amountMax, addTimeMin, addTimeMax, memberId, memberName, memberMobile, keyword);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }

    @GetMapping("/export")
    public void exportData(HttpServletResponse response, Integer tradeType,  String startDate, String endDate) {
        if(null == tradeType || tradeType < 0) {
            tradeType = 0;
        }
        LocalDateTime addTimeMin = null;
        LocalDateTime addTimeMax = null;
        if(StringUtils.isNotBlank(startDate)) {
            addTimeMin = UF.getDate(startDate);
        }
        if(StringUtils.isNotBlank(endDate)) {
            addTimeMax = UF.getDate(endDate);
        }

        List<BillBean> list = billService.query(tradeType, addTimeMin, addTimeMax);
        if(list != null && list.size() > 0) {
            if (tradeType == 1) {
                String[] columnNames = {"序号", "流水号", "手机号", "用户姓名", "收入说明", "金额（元）", "卖金时金价(元/克)", "手续费（元）", "实际金额（元）", "操作时间"};
                String[] columns = {"index", "orderId", "memberMobile", "memberName", "remark", "amount", "goldPriceMark", "fee", "actualAmount", "addTimeString"};
                String fileName = "充值详表";
                int index = 1;
                for (BillBean bean : list) {
                    bean.setIndex(index);
                    index++;
                    if (bean.getGoldPrice() == null || bean.getGoldPrice().doubleValue() == 0) {
                        bean.setGoldPriceMark("N/A");
                    } else {
                        bean.setGoldPriceMark(String.valueOf(bean.getGoldPrice()));
                    }
                }
                ExportExcelController<BillBean> export = new ExportExcelController<BillBean>();
                export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
            } else if (tradeType == 4) {
                String[] columnNames = {"序号", "流水号", "手机号", "用户姓名", "支出说明", "金额（元）", "买金时金价(元/克)", "手续费（元）", "实际金额（元）", "操作时间"};
                String[] columns = {"index", "orderId", "memberMobile", "memberName", "remark", "amount", "goldPriceMark", "fee", "actualAmount", "addTimeString"};
                String fileName = "提现详表";
                int index = 1;
                for (BillBean bean : list) {
                    bean.setIndex(index);
                    index++;
                    if (bean.getGoldPrice() == null || bean.getGoldPrice().doubleValue() == 0) {
                        bean.setGoldPriceMark("N/A");
                    } else {
                        bean.setGoldPriceMark(String.valueOf(bean.getGoldPrice()));
                    }
                }
                ExportExcelController<BillBean> export = new ExportExcelController<BillBean>();
                export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
            }
        }
    }

    /**
     * 查询活跃会员列表(后台)
     * @param  startTime	  开始时间
     * @param  endTime      结束时间
     * @param  channelId     渠道
     * @return			                分页数据
     */
    @RequestMapping(value = "findBuySellActiveMemberList" , method = GET)
    public SerializeObject<List<ActiveMemberBean>> findById(String startTime,String endTime,String channelId) {
        FinanceBillParam financeBillParam = new FinanceBillParam();
        financeBillParam.setStartTime(startTime);
        financeBillParam.setEndTime(endTime);
        financeBillParam.setChannelId(channelId);
        System.out.println("--------"+channelId);
        List<ActiveMemberBean> list = billService.findBuySellActiveMemberList(financeBillParam);
        return new SerializeObject<>(ResultType.NORMAL, list);
    }
}
